// 保持静态属性的包装组件，确保 Schema 中的 FormStep.StepPane 能被正确解析
import React, { useState, useMemo, useEffect } from 'react'
import { FormConsumer } from '@formily/react'
import { Space, Button } from 'antd'
import { FormStep as FormilyFormStep } from '@formily/antd'
import { useFieldSchema } from '@formily/react'
import createEvent, { useT } from '@designable/event-system'
import { SuspendedBottom } from '../SuspendedBottom'
import { observer } from '@formily/reactive-react'
import { SchemaApp } from '../index'

const WrappedFormStepBase = observer((props: any) => {
  const {
    submitExpression,
    style,
    backText,
    nextText,
    submitText,
    defaultCurrent,
  } = props
  const [totalSteps, setTotalSteps] = useState(0)
  const $t = useT()
  const fieldSchema = useFieldSchema()
  const formStep = useMemo(
    () => (FormilyFormStep as any).createFormStep?.(),
    []
  )
  useEffect(() => {
    if (fieldSchema) {
      const childrenProps = fieldSchema.properties || {}
      setTotalSteps(Object.keys(childrenProps).length)
    }
  }, [fieldSchema])

  return (
    <div style={style}>
      <FormilyFormStep
        formStep={formStep}
        current={Number(defaultCurrent) || 0}
      />
      <FormConsumer>
        {() => {
          const activeIndex = formStep.current || 0
          if (activeIndex === totalSteps - 1) {
            return null
          }
          const allowBack = activeIndex >= 1
          const allowNext = activeIndex < totalSteps - 2
          const allowSubmit = activeIndex === totalSteps - 2
          return (
            <SuspendedBottom>
              <Space
                style={{
                  marginTop: 12,
                  display: 'flex',
                  justifyContent: 'center',
                  width: '100%',
                }}
              >
                {allowBack && (
                  <Button
                    size="large"
                    onClick={() => {
                      formStep.back()
                    }}
                  >
                    {$t(backText || '上一步')}
                  </Button>
                )}
                {allowNext && (
                  <Button
                    size="large"
                    type="primary"
                    onClick={() => {
                      formStep.next()
                    }}
                  >
                    {$t(nextText || '下一步')}
                  </Button>
                )}
                {allowSubmit && (
                  <Button
                    size="large"
                    type="primary"
                    onClick={async () => {
                      try {
                        const values = await formStep.submit()
                        if (submitExpression) {
                          await createEvent(submitExpression as string, {
                            form: formStep,
                            values,
                            $t,
                          })
                          formStep.next()
                        }
                      } catch (e) {
                        // eslint-disable-next-line no-console
                        console.error('执行提交表达式失败:', e)
                      } finally {
                      }
                    }}
                  >
                    {$t(submitText || '提交')}
                  </Button>
                )}
              </Space>
            </SuspendedBottom>
          )
        }}
      </FormConsumer>
    </div>
  )
})

const Com = {
  StepPane: (props: any) => {
    const { title, subTitle, description, ...rest } = props || {}
    const $t = useT()
    const StepPane = (FormilyFormStep as any).StepPane
    return (
      <StepPane
        {...rest}
        title={$t(title)}
        subTitle={$t(subTitle)}
        description={$t(description)}
      />
    )
  },
  createFormStep: (FormilyFormStep as any).createFormStep,
}

const FormContainer = (props: any) => {
  const fieldSchema = useFieldSchema()
  fieldSchema['x-component'] = 'FormStepBase'
  const name = fieldSchema['x-designable-id']
  const schema = {
    type: 'void',
    properties: {
      [name]: fieldSchema,
    },
  }
  return (
    <SchemaApp
      pageSchema={{
        formProps: {},
        schema: schema,
      }}
    />
  )
}

export const FormStepBase = Object.assign(WrappedFormStepBase, Com)
export const FormStep: any = Object.assign(FormContainer, Com)
